package org.lex.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * StreamRedirector��һ�����л����ʵ��,���ں�̨����
 * 
 * @author Daniel Liu
 */
public class BufferedStreamRedirector implements StreamRedirector {
	private InputStream in = null;
	private OutputStream out = null;
	private int bufsize = IntConst.INT_32K;
	private byte[] buffer = null;
	private boolean aborted = false;
	// ==============================
	private long readBytesCount = 0L;
	private long writeBytesCount = 0L;

	public BufferedStreamRedirector() {
		this(IntConst.INT_32K);
	}

	public BufferedStreamRedirector(int bufferSize) {
		super();
		this.bufsize = bufferSize;
		this.buffer = new byte[this.bufsize];
	}

	public void resetCounter() {
		this.readBytesCount = 0L;
		this.writeBytesCount = 0L;
	}

	public long getReadBytesCount() {
		return this.readBytesCount;
	}

	public long getWriteBytesCount() {
		return this.writeBytesCount;
	}

	public void setInputStream(InputStream in) {
		this.in = in;
	}

	public void setOutputStream(OutputStream out) {
		this.out = out;
	}

	public void abort() {
		this.aborted = true;
	}

	public BufferedStreamRedirector call() throws IOException {
		int length = 0;
		this.aborted = false;
		while (false == aborted && ((length = this.in.read(buffer, 0, buffer.length)) != -1)) {
			this.readBytesCount += length;
			out.write(buffer, 0, length);
			this.writeBytesCount += length;
		}
		return this;
	}
}
